<!--
 * @Description: 首页 - 菜品和桌台管理
 * @Author: duan_shuangjun 丶
 * @Date: 2025-08-20 20:24:07
 * @LastEditTime: 2025-09-23 23:39:24
-->
<template>
  <div>
    <div class="content-wrap">
      <!-- 菜品相关的组件 -->
      <div class="left-box" v-loading="loading">
        <FoodModules
          :deskDetail="deskDetailData"
          @refreshDesk="handleRefreshDest"
          @refreshData="handleRefreshData"
          @openPractice="onOpenPractice"
        />
      </div>
      <div class="right-box">
        <!-- 右侧内容：做法面板 或 桌台组件 -->
        <PracticeFoodPanel
          v-if="showPracticePanel"
          :deskDetail="deskDetailData"
          :selectFoodActiveIndex="practiceSelectIndex"
          @refreshData="handleRefreshData"
          @close="showPracticePanel = false"
        />
        <!-- // 桌台 -->
        <DesktopModules
          v-else
          @selectTable="selectTable"
          :isFood="true"
          ref="desktopModulesRef"
          :selectedRecordId="route.params.id"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import FoodModules from './components/Food/Index.vue'
import DesktopModules from './components/Desktop/Index.vue'
import PracticeFoodPanel from './components/Food/SignleFoodAction/PracticeFoodPanel.vue'
import { fetchDeskDetail } from '@/api/desktop'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 当前选中的桌台详情ID
const deskDetailData = ref<any>(null)
// 加载状态
const loading = ref(false)
// 桌台相关的组件
const desktopModulesRef = ref<any>(null)
// 右侧内容切换：做法面板
const showPracticePanel = ref(false)
const practiceSelectIndex = ref(-1)

// 从左侧 FoodModules 打开右侧做法面板
const onOpenPractice = (index: number) => {
  practiceSelectIndex.value = index
  showPracticePanel.value = true
}

// 刷新桌台列表数据
const handleRefreshDest = () => {
  desktopModulesRef.value.getDeskListData(false)
}

// 获取桌台详情
const getDeskDetail = async (recordId: string | number) => {
  if (!recordId) return

  try {
    loading.value = true
    const res = await fetchDeskDetail({ record_id: recordId })
    if (res.status === 200 && res.data) {
      deskDetailData.value = res.data
      // 处理特殊字段，参考旧项目
      processDeskDetailData()
      console.log('deskDetailData.value', deskDetailData.value)
    } else {
      ElMessage.error('获取桌台详情失败')
      deskDetailData.value = null
    }
  } catch (error) {
    console.error('获取桌台详情失败:', error)
    ElMessage.error('获取桌台详情失败')
    deskDetailData.value = null
  } finally {
    loading.value = false
  }
}

// 处理桌台详情数据
const processDeskDetailData = () => {
  if (!deskDetailData.value) return

  // 处理菜品列表数据
  if (deskDetailData.value.foodList && deskDetailData.value.foodList.length > 0) {
    deskDetailData.value.foodList.forEach((item: any) => {
      // 处理做法数据
      item.making_Data = {}
      item.foodMakingTotalMoneyList = []

      if (item.making_list && item.making_list.length > 0) {
        item.making_list.forEach((data: any) => {
          item.making_Data[data.making_name] = {
            name: data.making_name,
            money: data.money,
            id: data.making_id
          }
          item.foodMakingTotalMoneyList.push(data.money)
        })
      }

      if (item.write_making && item.write_making.length > 0) {
        item.write_making.forEach((data: any) => {
          item.making_Data[data.name] = {
            name: data.name,
            money: data.money
          }
          item.foodMakingTotalMoneyList.push(data.money)
        })
      }
    })
  }

  // 处理酒席菜品列表
  if (
    deskDetailData.value.feastFoodList &&
    deskDetailData.value.feastFoodList.length > 0 &&
    deskDetailData.value.settle_type &&
    deskDetailData.value.settle_type.value === 10
  ) {
    // 深拷贝菜品列表
    const foodList = JSON.parse(JSON.stringify(deskDetailData.value.foodList || []))

    // 创建酒席数据
    const feastData = {
      banquetMoney: deskDetailData.value.money,
      banquetOpenNum: deskDetailData.value.open_num,
      banquetTotalMoney: (deskDetailData.value.money * deskDetailData.value.open_num).toFixed(2),
      banquetClerkName: deskDetailData.value.feastFoodList[0]?.clerk_name || '',
      banquetCreateTime: deskDetailData.value.feastFoodList[0]?.create_time || '',
      ...deskDetailData.value
    }

    // 添加到菜品列表前面
    foodList.unshift(feastData)
    deskDetailData.value.foodList = foodList
  }
}

const selectTable = (data: any) => {
  console.log('选中桌台:', data)
  router.push(`/home/food/${data?.recordInfo?.id}`)
}

// 处理数据刷新
const handleRefreshData = () => {
  console.log('刷新桌台详情数据')
  const id = route.params.id
  if (id) {
    getDeskDetail(id)
  }
}

// 监听路由参数变化，当ID改变时重新获取数据
watch(
  () => route.params.id,
  newId => {
    if (newId) {
      getDeskDetail(newId)
    }
  },
  { immediate: true }
)

onMounted(() => {
  // 组件挂载时也会触发watch，所以这里不需要重复调用
  // const id = route.params.id
  // getDeskDetail(id)
})

// 获取当前店铺开班状态
// const fetchDeskWorkStatus = async () => {
//   try {
//     // TODO: 实现获取桌台工作状态的逻辑
//     console.log('获取桌台工作状态')
//   } catch (error) {
//     console.error('获取桌台工作状态失败:', error)
//   }
// }

// 获取首次登录本地保持数据
// const fetchFirstLoginLocalKeepData = async () => {
//   try {
//     // TODO: 实现获取首次登录本地保持数据的逻辑
//     console.log('获取首次登录本地保持数据')
//   } catch (error) {
//     console.error('获取首次登录本地保持数据失败:', error)
//   }
// }
</script>

<style lang="scss" scoped>
.content-wrap {
  display: flex;
  align-items: flex-start;
  .left-box {
    margin-right: 30px;
  }
  .right-box {
    // flex: 1;
    width: 100%;
  }
}
</style>
